
package com.hlkj.pay.controller.common;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.alibaba.fastjson.JSONObject;
import com.hlkj.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.util.SignUtils;
import com.hlkj.pay.vo.common.req.SignHelperReq;
import com.hlkj.pay.vo.common.resp.SignHelperRsq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author HlpayTeam
 * @date 2024/09/12 11:32
 */
@Tag(name = "签名验签工具")
@RestController
@RequestMapping("/v1/common/helper")
@RequiredArgsConstructor
public class HelperSignController extends BaseController {

    @Operation(summary = "签名")
    @PostMapping("/sign")
    CommonResult<SignHelperRsq> sign(@Validated @RequestBody SignHelperReq signHelperReq) {
        String signContent = "";
        try {
            Map<String, Object> params = JSONObject.parseObject(signHelperReq.getContent(), HashMap.class);
            params.remove("sign");
            signContent = SignUtils.getSignContent(params);//签名串
        } catch (Exception e) {
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "字符串格式错误，只支持json格式");
        }
        try {
            String privateKey = signHelperReq.getRsaKey();
            String sign = SignUtils.generateSign(signContent, privateKey);//签名结果
            SignHelperRsq signHelperRsq = new SignHelperRsq();
            signHelperRsq.setSignContent(signContent);
            signHelperRsq.setSign(sign);
            return CommonResult.success(signHelperRsq);
        } catch (Exception e) {
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "签名失败，请检查私钥是否正确");
        }
    }

    @Operation(summary = "验签")
    @PostMapping("/verify")
    CommonResult<SignHelperRsq> verify(@Validated @RequestBody SignHelperReq signHelperReq) {
        Map<String, Object> params;
        try {
            params = JSONObject.parseObject(signHelperReq.getContent(), HashMap.class);
        } catch (Exception e) {
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "字符串格式错误，只支持json格式");
        }
        try {
            String sign = params.get("sign").toString();
            String content = SignUtils.getSignCheckContent(params);//验签串
            String publicKey = signHelperReq.getRsaKey();
            boolean flag = SignUtils.generateVerify(content, sign, publicKey);
            SignHelperRsq signHelperRsq = new SignHelperRsq();
            signHelperRsq.setSignContent(content);
            if (flag) signHelperRsq.setSign("验签通过");
            else signHelperRsq.setSign("验签失败");
            return CommonResult.success(signHelperRsq);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), "验签失败，请检查公钥是否正确");
        }
    }

    public static void main(String[] args) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("content", "{\"code\":\"00000000\",\"merchantNo\":\"XSSY20250314000009\",\"message\":\"成功\",\"outTradeNo\":\"D20250321134824875372544\",\"payBrand\":\"ALIPAY\",\"payFinishTime\":\"20250321135036\",\"tradeAmount\":\"1\",\"tradeFee\":\"0\",\"tradeNo\":\"2250321000000001340\",\"tradeStatus\":\"SUCCESS\",\"tradeSubject\":\"测试商品\",\"transNonce\":\"f3e872d36368432481b74d2c1d975471\"}");
            obj.put("rsaKey", "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCxGT4ILK09wUGipHo8v8cPpksHPRuZqG+5UWst9uVdSFhT8b1qSO4NMiXXr1lWtToGICT73oPAcpIKBS+PGuvxeIBY8L0C4zaxCL7NFuRn9BKTqoZYq5uC8nsPjGMW7sUD2vdLTcowMT4y2F1IqwGAnVQVE9tP3TXx/1iqz03uGUwbxBU3hy+lHYA/ixGkIzTrue7krkOT8Aislkw5TliWHTpR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N03BDgmB9I+byaF7KXnWEnlU4q7F6HkWEv7AxMCVxeDMNAabaKymg+6MCjrFzOObHJ4Rje/aDf2aK8PVHW00Z2ypIgxAoGBAPFfivT0jxbfSspz805Sieznf8AqvvEa7bVxBRtmaivoPfVloFTUYKXw0gr8B6pXqdNQFOKQdTh7kuCaQrR3z5Cm0RRilWATMLfq5FECi2UX4S80vhRjP97bRXOyMgiWJwFKjJTH+zFAzjtSC6ae25ISVU92+/O6Qrjvg+MyXB6+");

            String con = obj.toJSONString();
            SignHelperReq signHelperReq = JSONObject.parseObject(con, SignHelperReq.class);
            Map<String, Object> params = JSONObject.parseObject(signHelperReq.getContent(), HashMap.class);
            String privateKey = signHelperReq.getRsaKey();
            String signContent = SignUtils.getSignContent(params);//签名串
            String sign = SignUtils.generateSign(signContent, privateKey);//签名结果
            System.out.println("签名字符串 => " + signContent);
            System.out.println("签名结果 => " + sign);

            JSONObject obj1 = new JSONObject();
            obj1.put("content", "{\"code\":\"00000000\",\"merchantNo\":\"XSSY20250314000009\",\"message\":\"成功\",\"outTradeNo\":\"D20250321134824875372544\",\"payBrand\":\"ALIPAY\",\"payFinishTime\":\"20250321135036\",\"tradeAmount\":\"1\",\"tradeFee\":\"0\",\"tradeNo\":\"2250321000000001340\",\"tradeStatus\":\"SUCCESS\",\"tradeSubject\":\"测试商品\",\"transNonce\":\"f3e872d36368432481b74d2c1d975471\",\"sign\":\"H2SmHhClTXEF4AUe8MN27F1Bs+FDku+GgHCsomT4xBw7OJEq0NErlDc/6aJ9/kmzNr2mLcgNGXVX6Up96jBcdQc5S4ivD0ldoGEjB6RR8w3h6fm0kTyYPdB22iOkVqF5yrdNjjb7bEJuAe2nzW/ykz7repmBL8GkMx/xcITyJNvariRluMstFq2lt8UQFuT0bmAEqTUhdwo5Gyyq+TmHgJGTcG2dq9MiOBm5foBqoTlL6Eirw/oPero77/kTlyWeROUf4JTEzwBLD1WlO2ybAU9XGFWWOWPyXeuSvDvJIpGcDTsdxb7ra8wQP2ocr2ww99kUB1CEEpf+DAVEUjb7sw==\"}");
            obj1.put("rsaKey", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsRk+CCytPcFBoqR6PL/HD6ZLBz0bmahvuVFrLfblXUhYU/G9akjuDTIl169ZVrU6BiAk+96DwHKSCgUvjxrr8XiAWPC9AuM2sQi+zRbkZ/QSk6qGWKubgvJ7D4xjFu7FA9r3S03KMDE+MthdSKsBgJ1UFRPbT9018f9Yqs9N7hlMG8QVN4cvpR2AP4sRpCM067nu5K5Dk/AIrJZMOU5Ylh06UZQlL6ZJv6KGRY2flC15ZOMxK3mgE43U4eNLpCM0AlxZQgoxxzCWEqJ3CGjWleNIf1Ht1AaS7kWImRX/wEIl8n2asZDPgXBJpm+jYmxfHdMunCmruq1B/QwvZ1usJQIDAQAB");
            String con1 = obj1.toJSONString();
            SignHelperReq signHelperReq1 = JSONObject.parseObject(con1, SignHelperReq.class);
            Map<String, Object> params1 = JSONObject.parseObject(signHelperReq1.getContent(), HashMap.class);
            String publicKey = signHelperReq1.getRsaKey();
            String sign1 = params1.get("sign").toString();
//            params1.remove("sign");
            String signContent1 = SignUtils.getSignCheckContent(params1);//签名串
            System.out.println("签名字符串1 => " + signContent1);
            System.out.println("签名内容1 => " + sign1);
            boolean flag = SignUtils.generateVerify(signContent1, sign1, publicKey);
            System.out.println("验签结果1 => " + (flag ? "验签成功" : "验签失败"));

        } catch (Exception e) {
        }
    }

}
